package com.outsourcing.bottle.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.outsourcing.bottle.R;
import com.outsourcing.bottle.domain.LocationEntry;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.ui.BottleTipsActivity;
import com.outsourcing.bottle.ui.ChooseLocationTabsActivity;
import com.outsourcing.bottle.ui.ThrowBottleSettingActivity;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class CityFragment extends Fragment implements BasicUIEvent, Callback {

	private final int search_location = 2;
	private final int gain_bottle = 3;
	private final int gain_bottle_success = 4;
	private final int gain_bottle_error = 5;
	private final int throw_bottle = 6;
	
	private ListView listView;
	private ChooseLocationTabsActivity activity;
	private int currentItem;
	private List<LocationEntry> locations;
	private LocationAdapter adapter;
	private LocationEntry myLocation;
	
	private ImageView refresh;
	private EditText keywordView;
	private Handler handler;
	
	public CityFragment() {
		super();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler(this);
		this.activity = (ChooseLocationTabsActivity) getActivity();
		Bundle bundle = getArguments();
		if (bundle != null) {
			currentItem = bundle.getInt("currentItem");
		}
		UICore.eventTask(this, activity, search_location, "search_location", null);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.choose_location, null);
		listView = (ListView) view.findViewById(R.id.choose_location_list);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				LocationEntry entry = locations.get(arg2);
				if (activity.type.equals("try")) {
					UICore.eventTask(CityFragment.this,
							activity, gain_bottle, getString(R.string.init_data), entry);
				} else {
					UICore.eventTask(CityFragment.this,
							activity, throw_bottle, getString(R.string.init_data), entry);
				}
			}
		});
		refresh = (ImageView) view.findViewById(R.id.choose_location_refresh);
		refresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				search();
			}
		});
		keywordView = (EditText) view.findViewById(R.id.choose_location_search_edit);
		keywordView.setHint(R.string.choose_location_city);
		keywordView.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				search();
				return false;
			}
		});
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		adapter = new LocationAdapter();
		listView.setAdapter(adapter);
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case search_location:
			locate();
			getSearchLocation(obj == null ? "" : (String)obj);
			handler.sendEmptyMessage(search_location);
			break;
		case gain_bottle:
			LocationEntry entry = (LocationEntry) obj;
			gainBottle(entry);
			break;
		case throw_bottle:
			LocationEntry entry_throw = (LocationEntry) obj;
			Message msg = Message.obtain(handler, throw_bottle, entry_throw);
			handler.sendMessage(msg);
			break;
		default:
			break;
		}
	}
	
	public void search() {
		String keyword = keywordView.getText().toString().trim();
		UICore.eventTask(CityFragment.this, activity, search_location, getString(R.string.init_data), keyword);
	}
	
	private void locate() {
		myLocation = new LocationEntry();
		myLocation.setLatitude(AppContext.getInstance().getLatitude());
		myLocation.setLongitude(AppContext.getInstance().getLongitude());
		String params = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude());
		String language = AppContext.language == 1 ? "zh" : "en";
		String url = "http://www.mobibottle.com/openapi/geocode_offset.json?" +
				"latlng="+params+"&sensor=true&language=" + language + "&login_uid=" + AppContext.getInstance().getLogin_uid();
		try {
			String result = HttpUtils.doGet(url);
			JSONObject object = new JSONObject(result);
			JSONArray arrays = object.getJSONArray("results");
			for (int i = 0;i < arrays.length();i++) {
				JSONObject jsonObject = arrays.getJSONObject(i);
				if (jsonObject != null) {
					JSONArray addressArrays = jsonObject.getJSONArray("address_components");
					for (int j = 0;j < addressArrays.length();j++) {
						JSONObject obj = addressArrays.getJSONObject(j);
						JSONArray typeArray = obj.getJSONArray("types");
						for (int k = 0;k < typeArray.length();k++) {
							String typename = typeArray.getString(k);
							if (typename.equals("locality")) {
								myLocation.setCity(obj.getString("long_name"));
							} else if (typename.equals("administrative_area_level_1")) {
								myLocation.setProvince(obj.getString("long_name"));
							} else if (typename.equals("country")) {
								myLocation.setCountry(obj.getString("long_name"));
							}
						}
					}
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getSearchLocation(String keyword) {
		String url = "http://www.mobibottle.com/openapi/google_get_autocomplete.json?";
		String language = AppContext.language == 1 ? "zh" : "en" + "&login_uid=" + AppContext.getInstance().getLogin_uid();
		if (currentItem == 1) {
			String input = keyword + "+" + myLocation.getCountry() + "+" + myLocation.getProvince() + "+" + myLocation.getCity();
			url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey;
		} else if (currentItem == 2) {
			String input = keyword + "+" + myLocation.getCountry();
			url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey;
		} else if (currentItem == 3) {
			url += "input=" + keyword + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey;
		}
		System.out.println(url);
		try {
			String result = HttpUtils.doGet(url);
			JSONObject obj = new JSONObject(result);
			JSONArray arrays = obj.getJSONArray("predictions");
			locations = new ArrayList<LocationEntry>();
			for (int i = 0;i < arrays.length();i++) {
				LocationEntry entry = new LocationEntry();
				JSONObject object = arrays.getJSONObject(i);
				entry.setAddress(object.getString("description"));
				entry.setReference(object.getString("reference"));
				JSONArray typeArrays = object.getJSONArray("types");
				String type = typeArrays.getString(0);
				entry.setType(type);
				JSONArray termsArrays = object.getJSONArray("terms");
				JSONObject tearmObj = termsArrays.getJSONObject(0);
				entry.setLocationName(tearmObj.getString("value"));
				locations.add(entry);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void gainBottle(LocationEntry entry) {
		String url = UrlConfig.gain_bt;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("nettypeid", String.valueOf(activity.bottleId));
		paramsMap.put("bt_geo_lng", String.valueOf(entry.getLongitude()));
		paramsMap.put("bt_geo_lat", String.valueOf(entry.getLatitude()));
		paramsMap.put("bt_geo_reference", entry.getReference());
		try {
			String result = HttpUtils.doPost(activity, url, paramsMap);
			JSONObject obj = new JSONObject(result);
			JSONObject resultObj = obj.getJSONObject("results");
			int success = resultObj.getInt("success");
			if (success == 1) {
				String successmsg = resultObj.getString("successmsg");
				int gainbt_type = resultObj.getInt("gainbt_type");
				String gainbt_msg = resultObj.getString("gainbt_msg");
				Object[] objs = new Object[3];
				objs[0] = successmsg;
				objs[1] = gainbt_type;
				objs[2] = gainbt_msg;
				Message msg = Message.obtain(handler, gain_bottle_success, objs);
				handler.sendMessage(msg);
			} else {
				String errmsg = resultObj.getString("errmsg");
				Message msg = Message.obtain(handler, gain_bottle_error, errmsg);
				handler.sendMessage(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public class LocationAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return locations == null ? 0 : locations.size();
		}

		@Override
		public Object getItem(int arg0) {
			return locations == null ? null : locations.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			ViewHolder holder = new ViewHolder();
			if (convertView != null) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {
				view = LayoutInflater.from(activity).inflate(R.layout.choose_location_listitem, null);
				holder.nameView = (TextView) view.findViewById(R.id.choose_location_listitem_name);
				holder.vicinityView = (TextView) view.findViewById(R.id.choose_location_listitem_vicinity);
				holder.typeView = (TextView) view.findViewById(R.id.choose_location_listitem_type);
				view.setTag(holder);
			}
			LocationEntry entry = locations.get(position);
			if (entry != null) {
				holder.nameView.setText(entry.getLocationName());
				holder.vicinityView.setText(entry.getAddress());
				holder.typeView.setText(entry.getType());
			}
			return view;
		}
	}
	
	public static class ViewHolder {
		TextView nameView;
		TextView vicinityView;
		TextView typeView;
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case search_location:
			adapter = new LocationAdapter();
			listView.setAdapter(adapter);
			break;
		case gain_bottle_error:
			activity.onToast((String) msg.obj);
			break;
		case gain_bottle_success:
			Object[] objs = (Object[]) msg.obj;
			activity.onToast((String) objs[0]);
			Intent intent = new Intent(activity, BottleTipsActivity.class);
			intent.putExtra("type", "try");
			intent.putExtra("bottleId", Integer.parseInt(objs[1].toString()));
			intent.putExtra("gainbt_msg", objs[2].toString());
			startActivity(intent);
			break;
		case throw_bottle:
			LocationEntry entry = (LocationEntry) msg.obj;
			Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class);
			intent2.putExtra("bttype_id", activity.bottleId);
			intent2.putExtra("bt_geo_lng", entry.getLongitude());
			intent2.putExtra("bt_geo_lat", entry.getLatitude());
			intent2.putExtra("reference", entry.getReference());
			startActivity(intent2);
			break;
		default:
			break;
		}
		return false;
	}
}
